package com.by.service.impl;

import com.alibaba.excel.EasyExcel;
import com.by.bean.AccountDetail;
import com.by.bean.Enterprise;
import com.by.bean.XuFei;
import com.by.bean.excel.EnterpriseData;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.exception.BusinessException;
import com.by.mapper.AccountDetailMapper;
import com.by.mapper.EnterpriseCategoryMapper;
import com.by.mapper.EnterpriseMapper;
import com.by.service.EnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
public class EnterpriseServiceImpl extends BaseServiceImpl<Enterprise, EnterpriseMapper> implements EnterpriseService {

    private String currentMaxCode; //当前最大编码

    @Autowired
    AccountDetailMapper accountDetailMapper;

    @Autowired
    EnterpriseCategoryMapper enterpriseCategoryMapper;


    @Autowired
    HttpServletRequest request;

    @Override
    public Map queryMoney(int id) {
        return baseMapper.queryMoney(id);
    }

    @Transactional
    @Override
    public int xufei(XuFei xuFei) {
        //更新企业金额 及时间
        int rs = baseMapper.xufei(xuFei);
        if (rs == 0)
            throw new BusinessException("更新企业余额失败！");
        if (xuFei.getMonth() > 0) {
            //如果有增加会员日期  判断是否是首次购买会员 如果是 更新开通日期
            baseMapper.updateBeginDate(xuFei.getEid());
        }
        //更新成功了  添加账户变动明细
        AccountDetail detail = new AccountDetail();
        detail.setType(2);
        detail.setEid(xuFei.getEid());
        detail.setReason("企业续费" + xuFei.getMonth() + "个月");
        detail.setMoney(xuFei.getMoney());
        rs = accountDetailMapper.save(detail);


        return rs;
    }

    @Override
    public int auth(int id, int empNum, int accountNum) {
        return baseMapper.auth(id, empNum, accountNum);
    }

    @Transactional
    @Override
    public int save(Enterprise entity) {
        // 检查企业名称是否重复
        int count = baseMapper.existName(entity.getName());
        if (count > 0)
            throw new BusinessException("企业名称已存在");
        //可以用时 生成编码
        entity.setCode(generateNewCode());
        //保存企业
        int rs = super.save(entity);
        if (rs == 0)
            throw new BusinessException("保存企业失败");
        //更新类目数量
        rs = enterpriseCategoryMapper.addEnterpriseNum(entity.getCategoryCode());
        if(rs==0)
            throw new BusinessException("更新企业类数量失败");
        return 1;
    }

    /**
     * 生成新的编码
     *
     * @return
     */
    String generateNewCode() {
        //如果编码存在
        if (null != currentMaxCode) {
            return getNextCode(currentMaxCode);
        }

        //内存在没有 去数据库查询最大编码
        currentMaxCode = baseMapper.queryMaxCode();
        if (null == currentMaxCode) {
            //说明当前没有编码
            //赋值初始值
            currentMaxCode = "1000001";
            return currentMaxCode;
        }

        //如果存在
        return getNextCode(currentMaxCode);
    }

    /**
     * 根据当前编码 生成下一个编码
     *
     * @param currentCode 当前编码
     * @return
     */
    String getNextCode(String currentCode) {
        //如果内存中存在最大编码
        //转换编码 为数字
        int tmp = Integer.parseInt(currentCode);
        //编码加1
        tmp++;
        //记录最新的编码
        currentMaxCode = String.valueOf(tmp);
        return currentMaxCode;
    }


    @Override
    public String export(Map map) {
        //查询要导出的数据
        List<EnterpriseData> list = baseMapper.export(map);
        //获取服务器根目录
        String root = request.getServletContext().getRealPath("/") + "/excel";
        File file = new File(root);
        if (!file.exists())
            file.mkdirs();
        String newFileName = file.getAbsolutePath() + "/企业列表.xlsx";
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(newFileName, EnterpriseData.class)
                .sheet("模板")
                .doWrite(() -> {
                    return list;
                });
        return "/excel/企业列表.xlsx";
    }
}
